<?php

namespace plugin\ycMassage\app\api\controller;

use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageCoupon;
use plugin\ycMassage\app\model\MassageCouponCode;
use plugin\ycMassage\utils\enum\CouponCodeState;
use plugin\ycMassage\utils\enum\CouponReceiveType;
use plugin\ycMassage\utils\enum\State;
use support\Request;
use think\facade\Db;

class CouponController extends BaseController
{
    protected $noNeedLogin = ["receiveList"];
    public function receiveList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $saas_appid = $request->appid;
        if ($request->saas_appid) {
            $saas_appid = $request->saas_appid;
        }
        $uid = $request->uid;
        $where = [];
        $where[] = ['saas_appid', '=', $saas_appid];
        $where[] = ['state', '=', State::YES['value']];
        $receiveType = CouponReceiveType::getOptions();
        $receive = [];
        for ($i = 0; $i < count($receiveType); $i++) {
            if ($receiveType[$i]['value'] !== CouponReceiveType::BIND['value']) {
                $receive[] = $receiveType[$i]['value'];
            }
        }
        $where[] = ['receive_type', 'in', $receive];
        $list = MassageCoupon::where($where)
            ->order('id desc')
            ->page($page, $limit)
            ->select()->each(function ($item) use ($uid) {
                $item->money = (float)$item->money;
                $item->full_money = (float)$item->full_money;
                $item->is_receive = 0;
                $where = [];
                $where[] = ['uid', '=', $uid];
                $where[] = ['coupon_id', '=', $item->id];
                $model = MassageCouponCode::where($where);
                switch ($item->receive_type) {
                    case CouponReceiveType::DAY['value']:
                        $model->whereDay('receive_time');
                        break;
                    case CouponReceiveType::WEEK['value']:
                        if ($item->receive_day) {
                            $week = (int)date('w');
                            $receive_day = $item->receive_day > 6 ? null : $item->receive_day;
                            if ($item->receive_day && $receive_day != null && $receive_day != $week) {
                                $item->is_receive = 1;
                                $item->receive_tips = getWeekText((int)$receive_day) . '可领';
                                break;
                            }
                        }
                        $model->whereWeek('receive_time');
                        break;
                    case CouponReceiveType::MONTH['value']:
                        if ($item->receive_day) {
                            $receive_day = $item->receive_day == 99 ? date('t') : $item->receive_day;
                            $day = (int)date('d');
                            if ((int)$receive_day != $day) {
                                $item->is_receive = 1;
                                $item->receive_tips = $receive_day . '号可领';
                                break;
                            }
                        }
                        $model->whereMonth('receive_time');
                        break;
                    case CouponReceiveType::ONLY['value']:
                        break;
                }
                if ($item->is_receive === 0) {
                    $MassageCouponCode = $model->find();
                    if ($MassageCouponCode) {
                        $item->is_receive = 2;
                    }
                }
            });
        return $this->successRes($list);
    }
    public function receive(Request $request)
    {
        $uid = $request->uid;
        $couponId = $request->get('id');
        $MassageCoupon = MassageCoupon::where(['id' => $couponId, 'saas_appid' => $request->saas_appid, 'state' => State::YES['value']])->find();
        if (!$MassageCoupon) {
            return $this->fail('优惠券不存在');
        }
        if ($MassageCoupon->num <= 0) {
            return $this->fail('优惠券已领完');
        }
        $where = [];
        $where[] = ['uid', '=', $uid];
        $where[] = ['coupon_id', '=', $MassageCoupon->id];
        $model = MassageCouponCode::where($where);
        switch ($MassageCoupon->receive_type) {
            case CouponReceiveType::BIND['value']:
                return $this->fail('优惠券不存在');
            case CouponReceiveType::DAY['value']:
                $model->whereDay('receive_time');
                break;
            case CouponReceiveType::WEEK['value']:
                if ($MassageCoupon->receive_day) {
                    $week = (int)date('w');
                    $receive_day = $MassageCoupon->receive_day > 6 ? null : $MassageCoupon->receive_day;
                    if ($MassageCoupon->receive_day && $receive_day != null && $receive_day != $week) {
                        return $this->fail('该优惠券不能领取');
                    }
                }
                $model->whereWeek('receive_time');
                break;
            case CouponReceiveType::MONTH['value']:
                if ($MassageCoupon->receive_day) {
                    $receive_day = $MassageCoupon->receive_day == 99 ? date('t') : $MassageCoupon->receive_day;
                    $day = (int)date('d');
                    if ((int)$receive_day != $day) {
                        return $this->fail('该优惠券不能领取');
                    }
                }
                $model->whereMonth('receive_time');
                break;
            case CouponReceiveType::ONLY['value']:
                break;
        }
        $MassageCouponCode = $model->find();
        if ($MassageCouponCode) {
            return $this->fail('您已领取过该优惠券');
        }
        try {
            $MassageCouponCode = MassageCouponCode::where(['coupon_id' => $MassageCoupon->id])->whereNull('uid')->lock(true)->find();
            if (!$MassageCouponCode) {
                throw new \Exception('优惠券已领完');
            }
            MassageCouponCode::receive($MassageCoupon, $MassageCouponCode, $uid);
            return $this->success('领取成功');
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
    }
    public function getAvailable(Request $request)
    {
        $uid = $request->uid;
        $where = [];
        $where[] = ['uc.uid', '=', $uid];
        $where[] = ['uc.state', '=', 0];
        $coupon = MassageCouponCode::where($where)->alias('uc')
            ->where(function ($query) {
                $startTime = [
                    ['uc.start_time', '=', NULL],
                    ['uc.start_time', '<=', date('Y-m-d H:i:s')]
                ];
                $query->whereOr($startTime);
            })
            ->where(function ($query) {
                $endTime = [
                    ['uc.end_time', '=', NULL],
                    ['uc.end_time', '>=', date('Y-m-d H:i:s')]
                ];
                $query->whereOr($endTime);
            })
            ->join('massage_coupon c', 'uc.coupon_id = c.id AND c.state = 1')
            ->field('uc.code,c.money,c.use_type,c.full_money,c.title')
            ->order('c.money desc')
            ->select()->each(function ($item) {
                $item->money = (float)$item->money;
                $item->full_money = (float)$item->full_money;
            });
        if ($coupon->isEmpty()) {
            return $this->fail('没有可用优惠券');
        }
        return $this->successRes($coupon);
    }
    public function list(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $uid = $request->uid;
        $where = [];
        $where[] = ['uc.uid', '=', $uid];
        $state = $request->get('state', 'all');
        switch ($state) {
            case 'used':
                $where[] = ['uc.state', '=', CouponCodeState::NO['value']];
                break;
            case 'unused':
                $where[] = ['uc.state', '=', CouponCodeState::YES['value']];
                break;
            case 'expired':
                $where[] = ['uc.state', '=', CouponCodeState::EXPIRED['value']];
                break;
        }
        $coupon = MassageCouponCode::where($where)->alias('uc')
            ->join('massage_coupon c', 'uc.coupon_id = c.id AND c.state = 1')
            ->field('uc.state,uc.code,uc.end_time,c.money,c.use_type,c.full_money,c.title')
            ->order('c.money desc')
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ])->each(function ($item) {
                $item->money = (float)$item->money;
                $item->full_money = (float)$item->full_money;
            });
        if ($coupon->isEmpty()) {
            return $this->fail('没有可用优惠券');
        }
        return $this->successRes($coupon);
    }
}
